<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\result\Result;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Env;

class OssUpload extends BaseController
{

    protected $middleware = ['auth', 'checkPermission'];

    //上传图片到阿里云Oss
    public function index()
    {
        $file = request()->file('file');  //input name=image
        //要上传文件的临时路径
        $filePath = $_FILES['file']['tmp_name'];
        //$type = $_FILES['images']['type'];
        $type = $file->extension();
        // 尝试执行
        try {
            $accessKeyId = Env::get('aliyunoss.keyid');
            $accessKeySecret = Env::get('aliyunoss.keysecret');
            $endpoint = Env::get('aliyunoss.endpoint');
            $bucket = Env::get('aliyunoss.bucket');

            //实例化对象 将配置传入
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            //这里是有sha1加密 生成文件名 之后连接上后缀
            $fileName = sha1(date('YmdHis', time()) . uniqid()) . '.' . $type;
            //上传至阿里云的目录 为年+月/日的格式
            $pathName = date('Y-m/d') . '/' . $fileName;
            //执行阿里云上传 bucket名称,上传的目录,文件
            $result = $ossClient->uploadFile($bucket, $pathName, $filePath);
        } catch (OssException $e) {
            return json(['code' => 400, 'msg' => '上传失败' . $e->getMessage(), 'data' => '']);
        }
        //将结果输出
        return json(['code' => 200, 'msg' => '上传成功', 'data' => $result['info']['url']]);
    }
}
